const express = require('express');
const User = require('../models/User');
const Role = require('../models/Role');
const Department = require('../models/Department');
const auth = require('../middleware/auth');

const router = express.Router();

// 获取仪表板概览数据
router.get('/overview', auth, async (req, res) => {
  try {
    // 并行获取各种统计数据
    const [userStats, roleStats, departmentStats] = await Promise.all([
      User.getStats(),
      Role.getStats(),
      Department.getStats()
    ]);
    
    // 获取最近7天的用户注册趋势
    const { pool } = require('../config/database');
    const [recentUsers] = await pool.execute(`
      SELECT DATE(create_time) as date, COUNT(*) as count
      FROM users
      WHERE create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
      GROUP BY DATE(create_time)
      ORDER BY date
    `);
    
    // 获取部门用户分布
    const [departmentDistribution] = await pool.execute(`
      SELECT d.name, COUNT(u.id) as user_count
      FROM departments d
      LEFT JOIN users u ON d.id = u.department_id
      GROUP BY d.id, d.name
      ORDER BY user_count DESC
      LIMIT 10
    `);
    
    // 获取角色用户分布
    const [roleDistribution] = await pool.execute(`
      SELECT r.name, COUNT(u.id) as user_count
      FROM roles r
      LEFT JOIN users u ON r.id = u.role_id
      GROUP BY r.id, r.name
      ORDER BY user_count DESC
    `);
    
    // 获取系统状态
    const [systemStatus] = await pool.execute(`
      SELECT 
        (SELECT COUNT(*) FROM users WHERE status = 'active') as active_users,
        (SELECT COUNT(*) FROM users WHERE status = 'inactive') as inactive_users,
        (SELECT COUNT(*) FROM users WHERE DATE(create_time) = CURDATE()) as today_new_users,
        (SELECT COUNT(*) FROM users WHERE DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)) as yesterday_new_users
    `);
    
    res.json({
      success: true,
      message: '获取仪表板数据成功',
      data: {
        stats: {
          users: userStats,
          roles: roleStats,
          departments: departmentStats
        },
        trends: {
          recentUsers,
          systemStatus: systemStatus[0]
        },
        distribution: {
          departments: departmentDistribution,
          roles: roleDistribution
        }
      }
    });
  } catch (error) {
    console.error('获取仪表板数据错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取仪表板数据失败'
    });
  }
});

// 获取用户活跃度统计
router.get('/user-activity', auth, async (req, res) => {
  try {
    const { pool } = require('../config/database');
    
    // 获取最近30天的用户注册趋势
    const [registrationTrend] = await pool.execute(`
      SELECT DATE(create_time) as date, COUNT(*) as count
      FROM users
      WHERE create_time >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
      GROUP BY DATE(create_time)
      ORDER BY date
    `);
    
    // 获取用户状态分布
    const [statusDistribution] = await pool.execute(`
      SELECT status, COUNT(*) as count
      FROM users
      GROUP BY status
    `);
    
    // 获取用户创建时间分布（按月份）
    const [monthlyDistribution] = await pool.execute(`
      SELECT 
        DATE_FORMAT(create_time, '%Y-%m') as month,
        COUNT(*) as count
      FROM users
      WHERE create_time >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
      GROUP BY DATE_FORMAT(create_time, '%Y-%m')
      ORDER BY month
    `);
    
    res.json({
      success: true,
      message: '获取用户活跃度数据成功',
      data: {
        registrationTrend,
        statusDistribution,
        monthlyDistribution
      }
    });
  } catch (error) {
    console.error('获取用户活跃度数据错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取用户活跃度数据失败'
    });
  }
});

// 获取部门统计详情
router.get('/department-stats', auth, async (req, res) => {
  try {
    const { pool } = require('../config/database');
    
    // 获取部门用户数量统计
    const [departmentUserStats] = await pool.execute(`
      SELECT 
        d.id,
        d.name,
        d.code,
        COUNT(u.id) as user_count,
        COUNT(CASE WHEN u.status = 'active' THEN 1 END) as active_users,
        COUNT(CASE WHEN u.status = 'inactive' THEN 1 END) as inactive_users
      FROM departments d
      LEFT JOIN users u ON d.id = u.department_id
      GROUP BY d.id, d.name, d.code
      ORDER BY user_count DESC
    `);
    
    // 获取部门层级统计
    const [departmentHierarchy] = await pool.execute(`
      SELECT 
        CASE 
          WHEN parent_id IS NULL THEN '顶级部门'
          ELSE '子部门'
        END as level,
        COUNT(*) as count
      FROM departments
      GROUP BY level
    `);
    
    res.json({
      success: true,
      message: '获取部门统计数据成功',
      data: {
        departmentUserStats,
        departmentHierarchy
      }
    });
  } catch (error) {
    console.error('获取部门统计数据错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取部门统计数据失败'
    });
  }
});

// 获取角色统计详情
router.get('/role-stats', auth, async (req, res) => {
  try {
    const { pool } = require('../config/database');
    
    // 获取角色用户数量统计
    const [roleUserStats] = await pool.execute(`
      SELECT 
        r.id,
        r.name,
        r.code,
        COUNT(u.id) as user_count,
        COUNT(CASE WHEN u.status = 'active' THEN 1 END) as active_users,
        COUNT(CASE WHEN u.status = 'inactive' THEN 1 END) as inactive_users
      FROM roles r
      LEFT JOIN users u ON r.id = u.role_id
      GROUP BY r.id, r.name, r.code
      ORDER BY user_count DESC
    `);
    
    // 获取角色权限统计
    const [rolePermissionStats] = await pool.execute(`
      SELECT 
        r.name,
        COUNT(rp.permission) as permission_count
      FROM roles r
      LEFT JOIN role_permissions rp ON r.id = rp.role_id
      GROUP BY r.id, r.name
      ORDER BY permission_count DESC
    `);
    
    res.json({
      success: true,
      message: '获取角色统计数据成功',
      data: {
        roleUserStats,
        rolePermissionStats
      }
    });
  } catch (error) {
    console.error('获取角色统计数据错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取角色统计数据失败'
    });
  }
});

// 获取系统性能指标
router.get('/performance', auth, async (req, res) => {
  try {
    const { pool } = require('../config/database');
    
    // 获取数据库连接状态
    const connection = await pool.getConnection();
    const dbStatus = 'connected';
    connection.release();
    
    // 获取表大小信息
    const [tableSizes] = await pool.execute(`
      SELECT 
        TABLE_NAME as table_name,
        ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024), 2) AS size_mb,
        TABLE_ROWS as row_count
      FROM information_schema.TABLES 
      WHERE TABLE_SCHEMA = DATABASE()
      ORDER BY size_mb DESC
    `);
    
    // 获取最近的系统活动
    const [recentActivity] = await pool.execute(`
      SELECT 
        'users' as table_name,
        COUNT(*) as total_records,
        MAX(create_time) as last_updated
      FROM users
      UNION ALL
      SELECT 
        'roles' as table_name,
        COUNT(*) as total_records,
        MAX(create_time) as last_updated
      FROM roles
      UNION ALL
      SELECT 
        'departments' as table_name,
        COUNT(*) as total_records,
        MAX(create_time) as last_updated
      FROM departments
    `);
    
    res.json({
      success: true,
      message: '获取系统性能指标成功',
      data: {
        database: {
          status: dbStatus,
          tableSizes,
          recentActivity
        },
        server: {
          uptime: process.uptime(),
          memory: process.memoryUsage(),
          nodeVersion: process.version
        }
      }
    });
  } catch (error) {
    console.error('获取系统性能指标错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取系统性能指标失败'
    });
  }
});

module.exports = router; 